<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI API测试工具</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1, h2 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .test-container {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .test-result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        .test-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .test-path {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .response-status {
            margin-bottom: 10px;
        }
        .console-output {
            background-color: #2d2d2d;
            color: #e6e6e6;
            padding: 15px;
            border-radius: 4px;
            margin-top: 20px;
            font-family: monospace;
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <h1>AI API测试工具</h1>
    
    <div class="test-container">
        <h2>环境信息</h2>
        <div id="environment-info">加载中...</div>
        
        <h2>测试选项</h2>
        <div>
            <label for="question-input">测试问题:</label>
            <input type="text" id="question-input" value="测试AI接口" style="width: 300px; padding: 5px;">
            <button id="run-test-btn">运行所有测试</button>
        </div>
        
        <h2>测试结果</h2>
        <div id="test-results">点击上方按钮开始测试...</div>
        
        <div class="console-output">
                <div><strong>控制台输出:</strong></div>
                <div id="console-output"></div>
            </div>
            
            <div class="test-container">
                <h2>特定后端地址测试</h2>
                <div id="custom-backend-test">
                    <div>系统将自动测试从API工具中发现的后端地址: http://127.0.0.1:9205</div>
                </div>
            </div>
            
            <div class="test-container">
                <h2>推荐配置</h2>
                <div id="recommended-settings">
                    <div>测试完成后将显示推荐的前端配置</div>
                </div>
            </div>
    </div>

    <script>
        // 日志记录函数
        function log(message) {
            const consoleOutput = document.getElementById('console-output');
            const logEntry = document.createElement('div');
            logEntry.textContent = new Date().toLocaleTimeString() + ': ' + message;
            consoleOutput.appendChild(logEntry);
            consoleOutput.scrollTop = consoleOutput.scrollHeight; // 滚动到底部
            console.log(message);
        }
        
        // 显示环境信息
        function showEnvironmentInfo() {
            const envInfo = document.getElementById('environment-info');
            const isProduction = window.location.hostname !== 'localhost';
            
            envInfo.innerHTML = `
                <div><strong>当前环境:</strong> ${isProduction ? '生产环境' : '开发环境'}</div>
                <div><strong>当前URL:</strong> ${window.location.href}</div>
                <div><strong>预期API基础URL:</strong> ${isProduction ? '/prod-api' : '/dev-api'}</div>
                <div><strong>预期代理目标:</strong> http://localhost:8080</div>
                <div><strong>API测试工具中发现的后端地址:</strong> http://127.0.0.1:9205</div>
            `;
        }
        
        // 创建axios实例
        function createAxiosInstance(baseURL) {
            const axiosInstance = axios.create({
                baseURL: baseURL,
                timeout: 10000,
                headers: {
                    'Content-Type': 'application/json;charset=utf-8'
                }
            });
            
            // 请求拦截器
            axiosInstance.interceptors.request.use(config => {
                log(`请求: ${config.method.toUpperCase()} ${config.baseURL}${config.url}`);
                log(`请求数据: ${JSON.stringify(config.data)}`);
                return config;
            });
            
            // 响应拦截器
            axiosInstance.interceptors.response.use(response => {
                log(`响应: ${response.status} ${response.config.baseURL}${response.config.url}`);
                log(`响应数据: ${JSON.stringify(response.data)}`);
                return response;
            }, error => {
                if (error.response) {
                    log(`错误: ${error.response.status} ${error.config.baseURL}${error.config.url}`);
                    log(`错误数据: ${JSON.stringify(error.response.data)}`);
                } else if (error.request) {
                    log(`错误: 没有收到响应 ${error.config?.baseURL}${error.config?.url}`);
                } else {
                    log(`错误: ${error.message}`);
                }
                return Promise.reject(error);
            });
            
            return axiosInstance;
        }
        
        // 运行单个测试
        async function runSingleTest(path, question, baseURL) {
            const axiosInstance = createAxiosInstance(baseURL);
            
            try {
                log(`\n===== 开始测试路径: ${path} =====`);
                log(`代理目标: http://localhost:8080${path.replace(baseURL, '')}`);
                
                const startTime = Date.now();
                const response = await axiosInstance({
                    url: path,
                    method: 'post',
                    data: { question }
                });
                const endTime = Date.now();
                
                const result = {
                    path: path,
                    success: true,
                    status: response.status,
                    data: response.data,
                    time: endTime - startTime,
                    error: null
                };
                
                log(`测试成功: ${path} (${result.time}ms)`);
                return result;
            } catch (error) {
                const endTime = Date.now();
                const result = {
                    path: path,
                    success: false,
                    status: error.response?.status || 'N/A',
                    data: error.response?.data || null,
                    time: endTime - startTime,
                    error: error.message || '未知错误'
                };
                
                log(`测试失败: ${path} - ${result.error}`);
                return result;
            }
        }
        
        // 直接测试指定的后端地址
        async function testSpecificBackend(baseURL, path, question) {
            log(`\n===== 开始测试指定后端: ${baseURL}${path} =====`);
            
            const axiosInstance = createAxiosInstance(baseURL);
            
            try {
                const startTime = Date.now();
                const response = await axiosInstance({ 
                    url: path, 
                    method: 'post', 
                    data: { question } 
                });
                const endTime = Date.now();
                
                log(`测试成功: ${baseURL}${path} (${endTime - startTime}ms)`);
                log(`响应数据: ${JSON.stringify(response.data)}`);
                
                return { success: true, response, time: endTime - startTime };
            } catch (error) {
                log(`测试失败: ${baseURL}${path}`);
                if (error.response) {
                    log(`错误状态码: ${error.response.status}`);
                    log(`错误数据: ${JSON.stringify(error.response.data)}`);
                } else if (error.request) {
                    log(`错误: 没有收到响应 (可能是网络问题或服务未启动)`);
                } else {
                    log(`错误: ${error.message}`);
                }
                return { success: false, error };
            }
        }
        
        // 运行所有测试
        async function runAllTests() {
            const question = document.getElementById('question-input').value;
            const testResults = document.getElementById('test-results');
            testResults.innerHTML = '<div>正在运行测试，请稍候...</div>';
            
            // 清空控制台
            document.getElementById('console-output').innerHTML = '';
            
            const isProduction = window.location.hostname !== 'localhost';
            const baseURL = isProduction ? '/prod-api' : '/dev-api';
            
            // 测试不同的API路径组合
            const pathsToTest = [
                baseURL + '/api/chat',
                baseURL + '/ai/chat',
                baseURL + '/chat',
                '/api/chat',
                '/ai/chat',
                '/chat'
            ];
            
            // 去重
            const uniquePaths = [...new Set(pathsToTest)];
            
            log(`开始测试 ${uniquePaths.length} 个路径组合...`);
            
            const results = [];
            
            // 逐个测试
            for (const path of uniquePaths) {
                const result = await runSingleTest(path, question, baseURL);
                results.push(result);
            }
            
            // 显示结果
            let html = '<div>测试完成，共测试了 ' + results.length + ' 个路径:</div>';
            
            results.forEach(result => {
                html += `
                    <div class="test-item">
                        <div class="test-path">路径: ${result.path}</div>
                        <div class="response-status">
                            ${result.success ? 
                                '<span style="color: green;">✓ 成功</span>' : 
                                '<span style="color: red;">✗ 失败</span>'} 
                            (状态码: ${result.status}, 耗时: ${result.time}ms)
                        </div>
                        <div class="test-result ${result.success ? 'success' : 'error'}">
                            ${result.success ? 
                                '响应数据: ' + JSON.stringify(result.data, null, 2) : 
                                '错误信息: ' + result.error + '\n' + 
                                (result.data ? '错误详情: ' + JSON.stringify(result.data, null, 2) : '')}
                        </div>
                    </div>
                `;
            });
            
            // 找出成功的路径
            const successfulPaths = results.filter(r => r.success);
            if (successfulPaths.length > 0) {
                html += `
                    <div style="margin-top: 20px; padding: 15px; background-color: #e3f2fd; border-radius: 4px;">
                        <strong>推荐使用以下成功的路径:</strong>
                        <ul>
                            ${successfulPaths.map(r => `<li>${r.path} (耗时: ${r.time}ms)</li>`).join('')}
                        </ul>
                    </div>
                `;
            } else {
                html += `
                    <div style="margin-top: 20px; padding: 15px; background-color: #ffebee; border-radius: 4px;">
                        <strong>所有路径测试失败!</strong><br>
                        可能的原因:
                        <ul>
                            <li>后端服务未启动或端口不是8080</li>
                            <li>API路径配置错误</li>
                            <li>需要身份验证但未提供token</li>
                            <li>网络连接问题</li>
                        </ul>
                    </div>
                `;
            }
            
            testResults.innerHTML = html;
        }
        
        // 运行所有测试并添加特定后端测试
        async function runAllTestsWithSpecificBackend() {
            await runAllTests();
            
            // 额外测试API工具中发现的后端地址
            const question = document.getElementById('question-input').value;
            const customBackendTestResult = document.getElementById('custom-backend-test');
            customBackendTestResult.innerHTML = '<div>正在测试特定后端地址...</div>';
            
            const specificBackendBaseURL = 'http://127.0.0.1:9205';
            const specificBackendPath = '/api/chat';
            
            const result = await testSpecificBackend(specificBackendBaseURL, specificBackendPath, question);
            
            if (result.success) {
                customBackendTestResult.innerHTML = `
                    <div style="margin-top: 20px; padding: 15px; background-color: #d4edda; border-radius: 4px;">
                        <strong>✓ 特定后端地址测试成功!</strong><br>
                        <div>后端地址: ${specificBackendBaseURL}</div>
                        <div>API路径: ${specificBackendPath}</div>
                        <div>耗时: ${result.time}ms</div>
                        <div style="margin-top: 10px;">响应数据: ${JSON.stringify(result.response.data, null, 2)}</div>
                    </div>
                `;
                
                // 如果成功，将此地址添加到推荐列表
                document.getElementById('recommended-settings').innerHTML = `
                    <div style="margin-top: 20px; padding: 15px; background-color: #e8f5e9; border-radius: 4px;">
                        <strong>推荐前端配置:</strong>
                        <pre style="background-color: #f1f8e9; padding: 10px; border-radius: 4px; margin-top: 10px;">
// 在 ai.js 文件中使用以下配置
const directAxios = axios.create({
  baseURL: '${specificBackendBaseURL}',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})
                        </pre>
                    </div>
                `;
            } else {
                customBackendTestResult.innerHTML = `
                    <div style="margin-top: 20px; padding: 15px; background-color: #f8d7da; border-radius: 4px;">
                        <strong>✗ 特定后端地址测试失败!</strong><br>
                        <div>后端地址: ${specificBackendBaseURL}</div>
                        <div>API路径: ${specificBackendPath}</div>
                        <div>错误详情: ${result.error.message}</div>
                    </div>
                `;
            }
        }
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            showEnvironmentInfo();
            
            const runTestBtn = document.getElementById('run-test-btn');
            runTestBtn.addEventListener('click', runAllTestsWithSpecificBackend);
            
            // 自动运行测试
            setTimeout(runAllTestsWithSpecificBackend, 1000);
        });
    </script>
</body>
</html>